var fp = {
    setBtnStatus: function () {
        var row = $('#grid_fp').datagrid('getSelected');
        if (row && row.id && row.zt) {
            if (row.zt == 2) {
                // 已抛账
                $("#btn_fp_check_th").show();
                $("#btn_fp_dcjsgs").show();
                $("#btn_fp_tz").hide();
                $("#btn_fp_drjsgs").show();
                $("#btn_fp_check").hide();

            } else if (row.zt == 3) {
                // 已经提交
                $("#btn_fp_check").hide();
                $("#btn_fp_check_th").hide();
                $("#btn_fp_tz").hide();
                $("#btn_fp_dcjsgs").hide();
                $("#btn_fp_drjsgs").hide();
            } else if (row.zt == 4) {
                // 开票中
                $("#btn_fp_check_th").hide();
                $("#btn_fp_dcjsgs").hide();
                $("#btn_fp_drjsgs").show();
                $("#btn_fp_check").hide();
                $("#btn_fp_tz").show();
            } else if (row.zt == 5) {
                // 已开票
                $("#btn_fp_check_th").hide();
                $("#btn_fp_dcjsgs").hide();
                $("#btn_fp_drjsgs").hide();
                $("#btn_fp_check").show();
                $("#btn_fp_tz").hide();
            } else if (row.zt == 6) {
                // 冲销
                $("#btn_fp_check_th").hide();
                $("#btn_fp_dcjsgs").hide();
                $("#btn_fp_drjsgs").hide();
                $("#btn_fp_check").hide();
                $("#btn_fp_tz").hide();
            }
        } else {
            $("#btn_fp_check").hide();
            $("#btn_fp_check_th").hide();
            $("#btn_fp_tz").hide();
            $("#btn_fp_dcjsgs").hide();
            $("#btn_fp_drjsgs").hide();

        }
    },
    alwayShowDetail: function (rowData) {
        $('#layout_fp').layout('remove', 'center');
        var row = $('#grid_fp').datagrid('getSelected');
        if (row.type == 0) {
            $('#layout_fp').layout('add', {
                region: 'center',
                split: true,
                href: $.webPath() + '/jsgl/fp/fp_cgjsd_detail?fpcgjsdId=' + rowData.id
            });
        } else if (row.type == 1) {
            $('#layout_fp').layout('add', {
                region: 'center',
                split: true,
                href: $.webPath() + '/jsgl/fp/fp_xsjsd_detail?fpxsjsdId=' + rowData.id
            });
        } else {
            $('#layout_fp').layout('add', {
                region: 'center',
                split: true,
                href: $.webPath() + '/jsgl/fp/fp_wljsd_detail?fpwljsdId=' + rowData.id
            });
        }
    },
    showDetail: function (rowData) {
        if (rowData && $("#layout_fp").val() != rowData.id) {
            fp.alwayShowDetail(rowData);
        }
    }
}
$(function () {

    $("#fp_glqy").gsjgzcombobox();
    //表格初始加载
    $('#grid_fp').datagrid({
        url: $.webPath() + "/jsgl/fp/fpList",
        toolbar: "#toolbar_fp",
        pagination: true,
        rownumbers: true,
        checked: true,
        singleSelect: false,
        checkOnSelect: true,
        selectOnCheck: true,
        pageNumber: 1,
        collapsible: true,
        fit: true,
        fitColumns: true,
        columns: [
            [
                {field: 'checked', title: '选择', align: 'center', checkbox: true},
                {field: 'id', title: 'ID', align: 'center', hidden: true, width: $(this).width() * 0.1},
                {field: 'jsd_id', title: 'jsd_id', hidden: true},
                {field: 'jsdh', title: '结算单号', width: 40, align: 'center'},
                {field: 'sqrq', title: '申请日期', width: 30, align: 'center'},
                {field: 'type', title: '类型', width: 15, align: 'center',
                    formatter: function (value) {
                        if (value == '0')
                            return '采购';
                        if (value == '1')
                            return '销售';
                        if (value == '2')
                            return '物流';
                    }
                },
                {field: 'glqy_qc', title: '客户名称', width: 30, align: 'center'},
                {field: 'glqy_qyfr_nsh', title: '纳税号', width: 35, align: 'center'},
                {field: 'fpze', title: '发票总额(元)', width: 30, align: 'right',
                    formatter: function (value, row) {
                        if (row.zt == 3) {
                            return Math.round(row.swse * 100) / 100;
                        } else {
                            return Math.round(value * 100) / 100;
                        }

                    },
                    formatter: function (value, row) {
                        if (row.zt == 3) {
                            var sl = formatJe2(row.swse, ",");
                            return sl;
                        } else {
                            var sl = formatJe2(value, ",");
                            return sl;
                        }
                    }
                },
                {field: 'ddfy', title: '代垫运费(元)', width: 30, align: 'right',
                    formatter: function (value) {
                        var sl = formatJe2(value, ",");
                        return sl;
                    }
                },
                {field: 'fpzl', title: '发票种类', width: 18, align: 'center',
                    formatter: function (value) {
                        if (value == '0')
                            return '增票';
                        if (value == '1')
                            return '普票';
                        if (value == '2')
                            return '其他';
                        if (value == '3')
                            return '另开票';
                        if (value == '4')
                            return '物流发票';
                    }
                },
                {field: 'hm', title: '发票号码', width: 35, align: 'center'},
                {field: 'sqr_xm', title: '申请人', width: 15, align: 'center'},
                {field: 'kprq', title: '开票日期', width: 30, align: 'center'},
                {field: 'kpr_xm', title: '开票人', width: 15, align: 'center'},
                {field: 'gs_jc', title: '申报公司', width: 30, align: 'center'},
                {field: 'cggs_jc', title: '业务公司', width: 30, align: 'center'},
                {field: "zt", title: "状态", width: 25, align: 'center',
                    formatter: function (value) {
                        if (value == '0')
                            return '未抛账';
                        if (value == '1')
                            return '已退回';
                        if (value == '2')
                            return '已抛账';
                        if (value == '3')
                            return '已提交';
                        if (value == '4')
                            return '开票中';
                        if (value == '5')
                            return '已开票';
                    }}

            ]
        ],
        onLoadSuccess: function () {
            $(this).datagrid('selectRow', 0);
            fp.setBtnStatus();
            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        rowStyler: function (index, row) {
            if (row.sftzd == "是" && row.yjsd_id) {
                return 'background-color:rgba(255, 100, 87, 0.64);';
            }
        },
        onClickRow: function (rowIndex, rowData) {
            fp.setBtnStatus();
        },
        onSelect: function (rowIndex, rowData) {
            fp.showDetail(rowData);
            fp.setBtnStatus();
        }
    });
    //**********按钮触发事件**********
//    //新增按钮
//    $("#btn_fp_add").click(function () {
//        fp_add('新增销售单结算', 'add_fp');
//    });
//    //修改按钮
//    $("#btn_fp_mod").click(function () {
//        fp_modify('修改销售单结算', 'update_fp');
//    });
//    //删除按钮
//    $("#btn_fp_del").click(function () {
//        fp_delete();
//    });
    //确认按钮
//    $("#btn_fp_confirm").click(function () {
//        fp_confirm();
//    });
    // 审核按钮
    $("#btn_fp_check").click(function () {
        fp_check("发票提交");
    });
    //查询按钮
    $("#btn_fp_search").click(function () {
        fp_search();
    });
    //退回按钮
    $("#btn_fp_check_th").click(function () {
        fp_check_th("发票退回");
    });

    //取消审核
    $("#btn_fp_qxsh").click(function () {
        fp_qxsh();
    });

    //导出金税格式
    $("#btn_fp_dcjsgs").click(function () {
        fp_dcjsgs();
    });

    //导入金税格式
    $("#btn_fp_drjsgs").click(function () {
        fp_drjsgs();
    });

    //发票冲销
    $("#btn_fp_tz").click(function () {
        fp_tz();
    });

    //合同延期
    $("#btn_fp_xgshsj").click(function () {
        fp_xgshsj('修改审核时间', 'fp_xgshsj');
    });


    //加载查询条件中的申报公司下拉框
    $("#_gs").combotree({
        loadFilter: function (rows) {
            return convert(rows);
        }
    });
});


//发票审核
function fp_check(title, action) {
    var row = $('#grid_fp').datagrid('getSelected');
    if (row) {
        var href = $.webPath() + "/jsgl/fp/to_change_status?fpId=" + row.id;
        var actionUrl = $.webPath() + "/jsgl/fp/change_status";
        fp_check_showDialog(title, href, actionUrl);
    } else {
        $.messager.alert("提示", "请选择要审核的记录!", "warning");
        return;
    }
}

//发票审核退回
function fp_check_th(title, action) {
    var row = $('#grid_fp').datagrid('getChecked');
    if (row && row.length == 1 && row[0].zt == 2) {
        var href = $.webPath() + "/jsgl/fp/to_change_status_th?fpId=" + row[0].id;
        var actionUrl = $.webPath() + "/jsgl/fp/change_status_th";
        fp_check_th_showDialog(title, href, actionUrl);
    } else {
        $.messager.alert("提示", "请选择要退回的记录并且状态为抛账,只能选择一条!", "warning");
        return;
    }
}

function fp_qxsh() {
    var row = $('#grid_fp').datagrid('getSelected');
    if (row) {
        $.messager.confirm('提示', '是否取消审核付款单？', function (r) {
            if (r) {
                $.ajax({
                    url: $.webPath() + "/jsgl/fp/fp_qxsh",
                    dataType: 'text',
                    type: 'POST',
                    data: {fpId: row.id},
                    beforeSend: function () {
                        $("#fp_layout").mask();
                    },
                    success: function (data) {
                        $("#fp_layout").mask("hide");
                        if (data == '发票已取消审核!') {
                            $('#grid_fp').datagrid('reload');
                            $.messager.show({
                                title: '提示',
                                msg: data,
                                timeout: 3000,
                                showType: 'slide'
                            });
                        } else {
                            $.messager.alert("提示", data, "error");
                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选择要取消的发票！", "warning");
    }
}

// 冲销,作废
function fp_tz() {
    var row = $('#grid_fp').datagrid('getChecked');
    var fpIds = "";
    if (row && row.length > 0) {
        for (var i = 0; i < row.length; i++) {
            fpIds += row[i].id + ",";
        }
        $.messager.confirm('提示', '是否导出作废发票？', function (r) {
            if (r) {
                window.open($.webPath() + "/jsgl/fp/fptz?fpIds=" + fpIds);
            }
        });
    } else {
        $.messager.alert("提示", "请选择要作废的发票！", "warning");
    }
}

function fp_xgshsj(title, action) {
    var record = $('#grid_fp').datagrid('getSelected');
    if (record == null) {
        $.messager.alert("提示", "请选择要修改的销售时间!", "warning");
        return;
    }
    if (record.shzt == 0) {
        $.messager.alert("提示", "请选择已经审核过的发票修改时间!", "warning");
        return;
    }
    var href = $.webPath() + "/jsgl/fp/to_fp_xgshsj?fpId=" + record.id;
    var actionUrl = $.webPath() + "/jsgl/fp/fp_xgshsj";
    fp_xgshsjDialog(title, href, actionUrl);
}

// 导出金税格式
function fp_dcjsgs() {
    var row = $('#grid_fp').datagrid('getChecked');
    var fpIds = "";
    if (row && row.length > 0) {
        for (var i = 0; i < row.length; i++) {
            fpIds += row[i].id + ",";
        }
        $.messager.confirm('提示', '是否导出金税格式？', function (r) {
            if (r) {
                window.open($.webPath() + "/jsgl/fp/fp_dcjsgs?fpIds=" + fpIds);
            }
        });
    } else {
        $.messager.alert("提示", "请选择要导出金税格式的发票！", "warning");
    }
}

// 导入金税格式
function fp_drjsgs() {
    var win = $.window({
        title: "导入金税格式",
        width: 450,
        height: 240,
        cache: false,
        url: $.webPath() + "/jsgl/fp/fp_upload",
        modal: true,
        buttons: [
            {
                text: '导入',
                handler: function () {
                    $('#fp_uploadSubject').form('submit', {
                        onSubmit: function () {
                            var file = $("#upload").val();
                            var fileContentType = file.match(/^(.*)(\.)(.{1,8})$/)[3];
                            if (file) {
                                if (fileContentType.toLowerCase() != "txt") {
                                    alert("文件格式错误，请上传txt文件！");
                                    $(win).mask('hide');
                                    return false;
                                }
                            } else {
                                alert("请上传txt文件");
                                $(win).mask('hide');
                                return false;
                            }
                        },
                        success: function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#grid_fp').datagrid('reload');
                                $.messager.show({
                                    title: '提示',
                                    msg: json.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    })
}

//弹出发票审核的页面
function fp_check_showDialog(title, href, actionUrl) {
    var win = $.window({
        title: title,
        iconCls: 'icon-add2',
        width: 1024,
        height: 450,
        url: href,
        modal: true,
        buttons: [
            {
                text: '提交',
                handler: function () {
                    $(win).mask();
                    $('#form_fp_check').form('submit', {
                        url: actionUrl,
                        onSubmit: function (param) {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $(win).mask('hide');
                                return false;
                            }
                            //=================================
                            var row = $('#grid_fp').datagrid('getSelected');
                            if (row.type == 1) {
                                var data = $('#grid_xsd_fp').edatagrid("getData");
                                var xsdmxPrefix = 'fp.xsdmxList';
                                var paramString = "{";
                                for (var i = 0; i < data.rows.length; i++) {
                                    var objectString = $.toJSONStringSubPrefix(data.rows[i], xsdmxPrefix + "[" + i + "].", [
                                        ['je', 'jsbhse'],
                                        ['se', 'jsse'],
                                        ['ce', 'xsjsd.ce'],
                                        'id'
                                    ]);
                                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                                }
                                if (data.rows && data.rows.length > 0)
                                    paramString = paramString.substring(0, paramString.length - 1);
                                paramString += "}";
                                $.extend(param, $.parseJSON(paramString));
                            }
                            if (row.type == 2) {
                                var data = $('#grid_fp_wld').edatagrid("getData");
                                var xsdmxPrefix = 'fp.wldList';
                                var paramString = "{";
                                for (var i = 0; i < data.rows.length; i++) {
                                    var objectString = $.toJSONStringSubPrefix(data.rows[i], xsdmxPrefix + "[" + i + "].", [
                                        ['jsje', 'jsje'],
                                        ['se', 'se'],
                                        ['ce', 'ce'],
                                        ['kdse', 'kdse'],
                                        ['me', 'me'],
                                        'id'
                                    ]);
                                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                                }
                                if (data.rows && data.rows.length > 0)
                                    paramString = paramString.substring(0, paramString.length - 1);
                                paramString += "}";
                                $.extend(param, $.parseJSON(paramString));
                            }
                            return isValid;
                        },

                        success: function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#grid_fp').datagrid('reload');
                                $.messager.show({
                                    title: '提示',
                                    msg: json.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

function fp_xgshsjDialog(title, href, actionUrl) {
    var win = $.window({
        title: title,
        width: 420,
        height: 400,
        url: href,
        modal: true,
        buttons: [
            {
                text: '保存',
                handler: function () {
                    $(win).mask();
                    $('#form_fp_xgshsj').form('submit', {
                        url: actionUrl,
                        onSubmit: function () {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $(win).mask('hide');
                                return false;
                            }
                            return isValid;
                        },
                        success: function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#grid_fp').datagrid('reload');
                                $.messager.show({
                                    title: '提示',
                                    msg: json.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

//弹出发票退回的页面
function fp_check_th_showDialog(title, href, actionUrl) {
    var win = $.window({
        title: title,
        iconCls: 'icon-add2',
        width: 800,
        height: 450,
        url: href,
        modal: true,
        buttons: [
            {
                text: '退回',
                handler: function () {
                    $(win).mask();
                    $('#form_fp_check_th').form('submit', {
                        url: actionUrl,
                        onSubmit: function (param) {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $(win).mask('hide');
                                return false;
                            }
                            return isValid;
                        },
                        success: function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#grid_fp').datagrid('reload');
                                $.messager.show({
                                    title: '提示',
                                    msg: json.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}


//查询发票
function fp_search() {
    var glqyId = $('#fp_glqy').val() == null ? null : $('#fp_glqy').val();
    var glqyQc = $('#fp_glqy').attr("_text") == null ? null : $('#fp_glqy').attr("_text");
    /*   if(glqyQc==""){
     glqyId = null;
     }*/
    var gsId = $('#fp_gs').combotree('getValue') == null ? null : $('#fp_gs').combotree('getValue');
    var gsJc = $('#fp_gs').combotree('getText') == null ? null : $('#fp_gs').combotree('getText');
    var fpzlId = $('#fp_fpzl').combobox('getValue') == null ? null : $('#fp_fpzl').combobox('getValue');
    var sqrqStart = $('#fp_sqrq_start').datebox('getValue');
    var sqrqEnd = $('#fp_sqrq_end').datebox('getValue');
    var zt = $('#fp_zt').combobox('getValue') == null ? null : $('#fp_zt').combobox('getValue');
    var type = $('#fp_type').combobox('getValue') == null ? null : $('#fp_type').combobox('getValue');
    $('#grid_fp').datagrid('load',
        {
            jsdh: $('#fp_jsdh').val(),
            glqyId: glqyId,
            glqyQc: glqyQc,
            gsId: gsId,
            gsJc: gsJc,
            fpzlId: fpzlId,
            sqrqStart: sqrqStart,
            sqrqEnd: sqrqEnd,
            zt: zt,
            type: type
        }
    );
}

function getFirstDayofMonth(year, month) {
    var new_year = year;    //取当前的年份
    var new_month = month;//取下一个月的第一天，方便计算（最后一天不固定）
    var new_date = new Date(new_year, new_month, 1);                //取当年当月中的第一天
    return new_date;
}

function getFirstDayofNextMonth(year, month) {
    var new_year = year;    //取当前的年份
    var new_month = month++;//取下一个月的第一天
    if (month > 12) {
        new_month -= 12;        //月份减
        new_year++;            //年份增
    }
    var new_date = new Date(new_year, new_month, 1); //取当年当月中的第一天
    return new_date;
}
